import { expect } from '@jest/globals';
import fsExtra from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.AtomicService,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {}
};

const testFun: (module?: string) => TestCaseFun = (module?: string) => async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const entryModulePath = project.getModule('entry').moduleRootPath();

  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap'
    , ...(module ? { module: `${module}@default` } : {})
  });
  const result = await runHvigorAsync(projectRoot, commands);
  const buildPathExist =
    await fsExtra.pathExists(path.resolve(entryModulePath, 'build/default/outputs/default/entry-default-unsigned.hap'));

  const commandsApp = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp'
  });
  const resultApp = await runHvigorAsync(projectRoot, commandsApp, undefined, '@ohos/hvigor/bin/hvigor');
  const buildPathApp =
    await fsExtra.readdir(path.resolve(projectRoot, 'build/outputs/default'));
  const appPathExist = buildPathApp.some(item => path.extname(item) === '.app');

  record.addStep('执行hap编译构建', result);
  record.addStep('执行app编译构建', resultApp);
  expect(buildPathExist).toBe(true);
  expect(appPathExist).toBe(true);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  expect(resultApp.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_HOS_STAGE_Service_Project_build_api11_002')
  .description('hos-stage支持原子化服务工程编译 入口文件 @ohos/hvigor/bin/hvigor')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).ohpmInstall(IsEnable.Enable).build())
  .testFun(testFun('entry'))
  .load();
